package bigbanksystemserver.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.sql.Connection;
import java.sql.DriverManager;

public class ServerConnectionWrapper {

    byte[] dataReceived;
    byte[] dataSend;
    DatagramPacket packetReceived;
    DatagramPacket sendPacket;
    DatagramSocket udpSocket;
    File file = new File("src/bigbanksystemserver/utils/NetworkTopology.txt");

    public ServerConnectionWrapper() throws SocketException {
        this.dataSend = new byte[65536];
        this.dataReceived = new byte[65536];
        this.packetReceived = new DatagramPacket(dataReceived, dataReceived.length);
        this.sendPacket = new DatagramPacket(dataSend, dataSend.length);
        udpSocket = new DatagramSocket();
    }

    public void send(String data, InetAddress address, int port) {
        try {
            sendPacket.setAddress(InetAddress.getByName((address + "").replaceAll("/", "")));
            sendPacket.setPort(port);
            dataSend = data.getBytes();
            sendPacket.setData(dataSend);
            udpSocket.send(sendPacket);

        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("Wrapper : " + ex.getLocalizedMessage());
        }
    }

    //param receives current branchID and return the neigbor's branchID
    public String whoNeighbors(String currentBranch) {
        String line = null;
        int currentBranchIndex = 0;
        String neighborBranch = "";
        try {
            boolean isFound = false;
            BufferedReader br = new BufferedReader(new FileReader(file.getAbsolutePath()));
            line = br.readLine();
            String[] allBranches = line.split(" ");

            for (int i = 0; i < allBranches.length && !isFound; i++) {
                if (currentBranch.equals(allBranches[i])) {
                    isFound = true;
                    currentBranchIndex = i;
                }
            }
            currentBranchIndex++;
            neighborBranch = allBranches[currentBranchIndex % allBranches.length];
        } catch (FileNotFoundException ex) {
            System.out.println("Wrapper's WhoNeighbors FileNotFound :" + ex.getLocalizedMessage());
        } catch (IOException ex) {
            System.out.println("Wrapper's WhoNeighbors IOException :" + ex.getLocalizedMessage());
        }
        return neighborBranch;
    }
}
